<?php

#   UtilityKit
class UK
{

    public static function splitMapKey($key)/*{{{*/
    {
        $result =   explode('/', $key);
        if (count($result) > 2)
        {
            $tmp[0] =   $result[0];
            unset($result[0]);
            $tmp[1] =   implode('/', $result);
            $result =   $tmp;
        }
        return  $result;
    }/*}}}*/

    public static function getHashId($id, $baseNum, $code = NULL)/*{{{*/
    {
        $md5Id  =   md5($id);
		$decNum =   hexdec(substr($md5Id, -2));
		$result =   $decNum % $baseNum;
		return  $result;
    }/*}}}*/

    public static function saveLog($fileName, $string, $append = TRUE)/*{{{*/
    {
        file_put_contents ("/tmp/".$fileName, $string, FILE_APPEND);
    }/*}}}*/

    public static function varDump($param, $method = __METHOD__)/*{{{*/
    {
        return  NULL;
        $debug  =   AC::CODE_DEBUG;
        if (empty($debug))  return  NULL;

        echo "\r\n\t    method --> ", $method, ' , dump --> '; var_dump($param); echo "\r\n";
    }/*}}}*/

    public static function getBrowserType()/*{{{*/
    {
    	$agent = $_SERVER['HTTP_USER_AGENT'];
    	if (preg_match("MSIE", $agent, $array))
    	{
    		$client =   "Internet Explorer";
    	} 
    	else if (preg_match("Opera", $agent, $array))
    	{
    		$client =   "Opera";
    	}
    	else if (preg_match("Firefox", $agent, $array))
    	{
    		$client =   "Firefox";
    	}
    	else if (preg_match("Chrome", $agent, $array))
    	{
    		$client =   "Chrome";
    	}
    	else if (preg_match("Safari", $agent, $array))
    	{
    		$client =   "Safari";
    	}
    	else
    	{
    		$client =   "UnKnown";
    	}
    	return $client;
    }/*}}}*/

    /**
     * 截取中文,并将空格去掉
     * @param $string
     * @param $length
     * @param string $te
     * @param int $clean
     * @return mixed|string
     */
    public static function getstr($string, $length, $te='', $clean=0) {
        //3个或更多换行替换成2个
        $string = preg_replace("/\s*([\r\n]{3,})/","\n\n", $string);
    	if ($clean == 1){
    	    // 换行替换为单个空格，多空格替换为单空格
    	    $string = UK::cleanStr($string);
    	} else if($clean == 2) {
            // 严格过滤特殊转义字符
            $string = UK::cleanStrStrict($string);
        } else if($clean == 3) {
    	    $string = UK::replaceString($string);
        }
        $string = trim($string);
        $string = preg_replace("@<[\/\!]*?(link|meta|ifr|fra|script)[^<>]*?>@",'',$string);
        $string = UK::removeEmoji($string);

        if($length && strlen($string) > $length) {
            //截断字符
            $wordscut = '';
            //utf8编码
            $n = 0;
            $tn = 0;
            $noc = 0;
            while ($n < strlen($string)) {
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1;
                    $n++;
                    $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif(224 <= $t && $t < 239) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) {
                    break;
                }
            }
            $wordscut = substr($string, 0, $n);
            $string = $wordscut.$te;
        }
        $string = self::removeBadLanguage(trim($string));
        return $string;
    }
    
    public static function cleanStr($string)/*{{{*/
    {
        $string = str_replace(array("\r\n", "\n", "\r"), ' ', $string);
        return preg_replace('([ ]+)', ' ', $string);
    }
    public static function cleanStrStrict($string) {
        $string = str_replace(array("\r\n", "\n", "\r", "\t"), ' ', $string);
        return preg_replace('([ ]+)', ' ', $string);
    }
    public static function repalceStr($string){
    	$string = str_replace(array("\r\n", "\n", "\r"),array("\\r\\n", "\\n", "\\r"), $string);
    	return $string;
    }
    public static function replaceString($string){
        $string = str_replace("\\","\\\\", $string);
        return $string;
    }
    public static function removeEmoji($text) {
        //干掉所有四字节的字符
        $text = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $text);

        return $text;
    
//        $clean_text = " ";
//
//        // Match Emoticons
//        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
//        $clean_text = preg_replace($regexEmoticons, '', $text);
//
//        // Match Miscellaneous Symbols and Pictographs
//        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
//        $clean_text = preg_replace($regexSymbols, '', $clean_text);
//
//        // Match Transport And Map Symbols
//        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
//        $clean_text = preg_replace($regexTransport, '', $clean_text);
//
//        return $clean_text;
    }
    public static function removeBadLanguage($string)
	{
		$string = str_replace(ChatFilter::$filter,'**',$string);
		return $string;
	}
    public static function array_random_assoc($arr, $num = 1){
    	$keys = array_keys($arr);
    	shuffle($keys);
    	if(count($keys)<$num) $num = count($keys);
    		
    	$r = array();
    	for ($i = 0; $i < $num; $i++) {
    		$r[$keys[$i]] = $arr[$keys[$i]];
    	}
    	return $r;
    }
    
    public static function var_json_encode($var) {
        $_var = UK::var_urlencode($var);
        $_str = json_encode($_var);
        return urldecode($_str);
    }
    
    public static function var_urlencode($var) {
        if (empty ( $var )) {
            return false;
        }
        // 判断是否为数组
        if(is_array ($var)){
            foreach ($var as $k => $v ) {
                // is_scalar : 检测变量是否为标量
                if (is_scalar ($v)) {  // if用来处理不是数组的情况
                    $var [$k] = urlencode ($v );
                }
                else {//else用来处理数组
                    $var [$k] = UK::var_urlencode ( $v );
                }
            }
        }else {//用来处理数组
            $var = urlencode ( $var );
        }
        return $var;
    }
    
    public static function get_text($text){
    
        $arr = explode("\n", $text);
        $tt = array();
        foreach ($arr as $i=>$aa){
            if(!($i > 0 && trim($aa) ==""  && trim($arr[$i - 1]) == "")){
                $tt[] = $aa;
            }
        }
    
        $connent = implode("\n", $tt);
    
        return $connent;
    }
    
    public static function getHttpResponsePOST($url, $para, $input_charset = '') {
    	$curl = curl_init($url);
    	curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
    	curl_setopt($curl,CURLOPT_POST,true); // post传输数据
    	curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
    	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    	curl_setopt($curl, CURLOPT_USERAGENT, "FFWEB_1.0-API");
    	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
    	curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    	curl_setopt($curl, CURLOPT_ENCODING, "");
    	curl_setopt($curl, CURLOPT_HEADER, FALSE);
    	$responseText = curl_exec($curl);
    
    	// var_dump( curl_error($curl) );exit;//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    	curl_close($curl);
    	return $responseText;
    }
    
    public static function getHttpResponseGET($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        $responseText = curl_exec($curl);
        curl_close($curl);
        
        return $responseText;
    }
    
    public static function parseData($result){
    	return json_decode($result, true);
    }
    
    public static function tipsUpgrade($value, $content, $type){
    	if (!empty($value) && AC::$userVoiceVersion == 0 && $type == "voice"){
    		return "想听到Ta的声音吗?\n快去下载粉粉最新版本吧~\n\n".$content;
    	}
    	if (!empty($value) && AC::$topicFdVersion == 0 && $type == "topicFd"){
    	    return "想要查看话题详情？\n快去下载粉粉最新版本吧~\n\n".$content;
    	}
    	if (!empty($value) && AC::$chatAttachmentVersion == 0 && $type == "attachment"){
    	    return "快去下载粉粉最新版本查看图片或语音信息吧~\n\n".$content;
    	}
        if (!empty($value) && AC::$video_version == 0 && $type == "video"){
            return "下载粉粉最新版，玩转短视频新技能！\n\n".$content;
        }
    	return $content;
    }
    
    public static function check_upyun_node($uid, $account, $path) {
        $mded = md5($uid);
        $len = strlen($mded);
        $name = "/".substr($mded, $len-6, 2)."/".substr($mded, $len-4, 2)."/".substr($mded, $len-2, 2)."/";
        $combine = strtoupper($name);
        if (strpos('a'.$path, $combine) == 1 && strlen($path) > strlen($combine)){
            return TRUE;
        }
        
        $mded1 = md5($account.$uid);
        $len1 = strlen($mded1);
        $name1 = "/".substr($mded1, $len1-6, 2)."/".substr($mded1, $len1-4, 2)."/".substr($mded1, $len1-2, 2)."/";
        $combine1 = strtoupper($name1);
        if (strpos('a'.$path, $combine1) == 1 && strlen($path) > strlen($combine1)){
            return TRUE;
        }
        
        return FALSE;
    }

    /**
     * 验证表情云
     * @param $path(http://oe7ipw0lj.bkt.clouddn.com/@/emoticonPacket/f68617f3cfce4789a3b56df26080c6c7/thumicon/1478153465341_11.png)
     * @return bool
     */
    public static function check_bqyun($path) {
        $pattern = "/^(http:\/\/|https:\/\/).*$/";
        $domain  = "emoticonPacket";

        if (preg_match($pattern,$path)){
            return true;
        }

        return false;
    }
    
    public static function getuseravatarurl($uid, $avatar = ''){
        $base   =  AC::getProtocolUriByOS("http://icon.fenfenriji.com");
        if (!preg_match("/\//", $avatar)){
            $mded   =  strtoupper(md5($uid));
            $len    =  strlen($mded);
    
            $result =  "/".substr($mded, $len-6, 2)."/";
            $result =  $result.substr($mded, $len-4, 2)."/";
            $result =  $result.substr($mded, $len-2, 2)."/".$uid."/".$uid.".png!icon?";
            $result = $base.$result;
            $hashTime   =   substr(md5($avatar),-5);
            return $result.$hashTime;
        }
        $result =  $base.$avatar.'!icon';
        return  $result;
    }

    public static function getUserBackground($uid, $background){

        $base   =  AC::getProtocolUriByOS("http://icon.fenfenriji.com");
        if (!preg_match("/\//", $background)){
            $mded   =  strtoupper(md5($uid));
            $len    =  strlen($mded);

            $result =  "/".substr($mded, $len-6, 2)."/";
            $result =  $result.substr($mded, $len-4, 2)."/";
            $result =  $result.substr($mded, $len-2, 2)."/".$uid."/background.png!default?";

            $result =  $base.$result;
            $hashId =  substr(md5($background), -5);

            return $result.$hashId;
        }

        $result =  $base.$background;
        return  $result;
    }
    
    public static function getClientIp()/*{{{*/
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))    $ip =   $_SERVER['HTTP_X_FORWARDED_FOR'];
        elseif (isset($_SERVER['HTTP_REMOTEIP']))       $ip =   $_SERVER['HTTP_REMOTEIP'];
        elseif (isset($_SERVER['REMOTE_ADDR']))         $ip =   $_SERVER['REMOTE_ADDR'];

        empty($ip)  &&  $ip =   '127.0.0.1';
        return  $ip;
    }/*}}}*/

    public static function getDataByBodyid($type, $bodyId, $fields = ' * ')/*{{{*/
    {
        if (empty(AC::$bodyidTypeCode[$type]))  return  NULL;

        $code   =   AC::$bodyidTypeCode[$type];
        return  Storage::getDataByBodyid($code, $bodyId, $fields);
    }/*}}}*/

    public static function getBodyidByItemid($key, $itemId)/*{{{*/
    {
        if (empty($itemId)) return  FALSE;
        $dbInfo =   AC::getDbClient($key);
        if (empty($dbInfo)  ||  !isset($dbInfo['tableSuffix'])) return  FALSE;

        return  $itemId * 1000 + $dbInfo['tableSuffix'];
    }/*}}}*/

    public static function getItemidByBodyid($bodyId)/*{{{*/
    {
        if (empty($bodyId))     return  FALSE;
        $info['tableIndex'] =   $bodyId % 1000;
        $info['itemId']     =   floor($bodyId / 1000);
        return  $info;
    }/*}}}*/
    
    // 组装从数据库返回的数据，(不需要特殊处理,直接返回替换字段后的数据)
    public static function assembleReplacedFieldData ($import, &$result, $key_arr = array()) {
        if (empty($key_arr)) {
            return $result;
        }
    
        foreach ($key_arr as $key=>$val) {
            if (isset($import[$key])) {
                $result[$val] = strval($import[$key]);
            }
        }
    
        return $result;
    }

    public static function getMicroTime()/*{{{*/
    {
        list($usec, $sec)   =   explode(" ", microtime());
        return  ((float)$usec + (float)$sec);
    }/*}}}*/

    public static function isEmail($email)/*{{{*/
    {
        if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$email)){
            return true;
        }
        return false;
    }/*}}}*/

    public static function isFenFenId($id){
        if(!is_numeric($id)){
            return false;
        }
        if(strlen($id)<7 || strlen($id)>10){
            return false;
        }
        return true;
    }
    
    // 验证手机号是否合法(86-131********)
    public static function isMobile($phone) {
        
        list($area, $mobile) = explode('-', $phone);
        
        if (!is_numeric($mobile)) {
            return false;
        }

        if(!in_array($area, array(86))) {
            return false;
        }

        if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
            return false;
        }
        
        return true;
     }
     
     public function getMobileCodeType($type, $app = 0) {
         
         $result = 0;
         $validTypes = array(
             'mobile_register' => 1, 
             'mobile_bind' => 2, 
             'mobile_resetpasswd' => 3,
             'mobile_signup' => 4,
             'mobile_update' => 5,
             'mobile_signin' =>6,
             'mobile_withdrawal' =>7,
			 'mobile_setwithdrawal' =>8,
         );
         if ($app) {
             $validTypes = array(
                 'mobile_register' => 11,
                 'mobile_bind' => 12,
                 'mobile_resetpasswd' => 13,
                 'mobile_signup' => 14,
                 'mobile_update' => 15
             );
         }
	 
         $keys = array_keys($validTypes);
         if (in_array($type, $keys)) {
             $result = $validTypes[$type];
         }
         
         return $result;
     }

    public function getSmsCnf($appName)
    {
        $smsConf = AC::$smsApp[$appName];
        if (empty($smsConf)) return array();

        return $smsConf;
    }
    
    // 生成指定长度验证码
    public static function generateCode($length = 6) {
        return rand(pow(10,($length-1)), pow(10,$length)-1);
    }
    
    public static function parse_query($query) {
    	$queryParts = explode('&', $query);
 
    	$params = array();
  	    foreach ($queryParts as $param) {
            $item = explode('=', $param);
            if (empty($item[0])) continue;
 	        $params[$item[0]] = $item[1];
 	    }
   		
 	    return $params;
     }
     
     public static function getThirdPartyUser($platform, $openUid) {
         return  'open-'. $platform. '-'. $openUid;
     }
     
     public static function getMobileUser($mobile) {
         return  'mobile-'. $mobile;
     }
     
     public static function getAccountTpye($account){
 	 	
         $type = AC::ACCOUNT_TYPE_FENFEN_ACCOUNT;
        if(preg_match("/^(open-qq).*/", $account)){
            $type = AC:: ACCOUNT_TYPE_QQ;
        }elseif(preg_match("/^(open-weibo).*/", $account)){
            $type = AC:: ACCOUNT_TYPE_WEIBO;
        }elseif(preg_match("/^(open-wechat).*/", $account)){
            $type = AC:: ACCOUNT_TYPE_WECHAT;
        }elseif(preg_match("/^\d{7,10}+$/", $account)){
            $type = AC::ACCOUNT_TYPE_FENFEN_ID ;
        }elseif(UK::isMobile(substr($account, strlen('mobile-')))) {
            $type = AC::ACCOUNT_TYPE_MOBILE;
        }

        return $type;
    }
    
    public static function getAccountBindTypeOrOpenType ($type, $getOpenType = false) {
        $accountTypeConfig = AC::$accountTypeConfig;
        
        if ($getOpenType) {
            $accountTypeConfig = array_flip($accountTypeConfig);
            $result = isset($accountTypeConfig[$type]) ? $accountTypeConfig[$type] : 'fenfen';
        }else{
            $result = isset($accountTypeConfig[$type]) ? $accountTypeConfig[$type] : AC::ACCOUNT_TYPE_FENFEN_ACCOUNT;
        }
        
        return $result;
    }
    
    public static function makeRandPasswd()/*{{{*/
    {
        $seedString =   'abcdefghijkmnpqrstuvxxyz23456789';
        $seedLength =   strlen($seedString);
    
        $tmpString  =   NULL;
        for ($i =0; $i < 8; $i++)
        {
        $tmpString  .=  $seedString[rand(0, ($seedLength - 1))];
        }
    
        return  $tmpString;
    }/*}}}*/
    
    public static function cryptPasswd($account, $passwd) {
        $passwd         =   strtolower($passwd);
        $cryptPasswd    =   md5(md5($account). $passwd);
        return  $cryptPasswd;
    }
    
    // 判断用户设备的操作系统
    public static function checkOS($deviceOS)/*{{{*/
    {
        $deviceOS = strtolower($deviceOS);
        if (empty($deviceOS) || (substr($deviceOS,0,7) == 'android')){
            $sn    =   '1';
            return $sn;
        }
        $dev =  substr($deviceOS,0,4);
        if ($dev == 'ipho' || $dev == 'ipod' || $dev == 'ios'){
            $sn    =   '2';
        }
    
        return $sn;
    }

    public static function getOsAndPlantform ($extra) {
        $OS        = UK::checkOS($extra['appInfoList'][2]);
        $platform = 'android';

        // ios区分
        if ($OS == 2) {
            $platform = 'ios';
            if ($extra['appInfoList'][0] == 'pinkdiarypro') {
//                $platform = 'ios_pro';
            }
        }

        return array($OS, $platform);
    }
    
    // init mall sdk
    public static function getMallApi($uid){
        $userAuth = UserAuth::factory($uid, 'no token');
        $api = MallApi::instance($userAuth);
        return $api;
    }
    
    // 判断是否是当天
    public static function isToday($time){
        if(empty($time)){
            return false;
        }
        
        $curDate = date("Y-m-d");
        $time    = date("Y-m-d",$time);
        $publishDate = substr($time, 0, 10);
        if($curDate === $publishDate){
            return true;
        }
        return false;
    }
    
    // 判断是否是当月
    public static function isCurrentMonth($time){
        if(empty($time)){
            return false;
        }
        
        $currentDate = date('Y-m', strtotime(date("Y-m-d")));
        $timeDate    = date('Y-m', $time);

        if ($currentDate != $timeDate) {
            return FALSE;
        }
        
        return TRUE;
    }
    
    public static function replaceNickname ($nickname, $uid) {
        if(($uid < 10000) || preg_match('/^粉粉用户/u', $nickname)) {
            return $nickname;
        }
        return preg_replace('/^(粉粉|粉币)/u','**',$nickname);
    }
    
    public static function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                UK::arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }
    
            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
    }
    
    public static function JsonFormat($array) {
        UK::arrayRecursive($array, 'urlencode', true);
        $json = json_encode($array);
        return urldecode($json);
    }
    
    // 分页相关
    public static function assemblePageData ($param, $default_length = 0) {
        // 分页数据处理
        $id       =    0;
        $start    =    0;
        $length   =    $default_length ? $default_length : AC::DIARY_LIST_DEFAULT_LEN;
        isset($param['id'])        &&    $id        =    intval($param['id']);
        isset($param['start'])     &&    $start     =    intval($param['start']);
        isset($param['length'])    &&    $length    =    intval($param['length']);
        if ($start < 0 || $id > 0)    $start    =    0;
        if ($start < 0 )     $start     =    0;
        if ($length < 0 )    $length    =    AC::DIARY_LIST_DEFAULT_LEN;
    
        return array($id, $start, $length);
    }
    
    // 处理计数，返回正整数
    public static function intDeal ($num) {
        return strval(abs(intval($num)));
    }
 	
    // 判断是否是json格式
    public static function isJSON($string){
        return is_string($string) && is_object(json_decode($string)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
    }
    
    // 生成兑吧签名
    public static function generateDuiBaSign($array) {
        ksort($array);
        $string = "";
        while (list($key, $val) = each($array)){
            $string = $string . $val ;
        }
        return md5($string);
    }

    public static function sortArrByOneField(&$array, $field, $desc = true){
        $sort = array(
            'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field'     => $field,       //排序字段
        );
        $arrSort = array();
        foreach($array AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $array);
        }

        return $array;
    }

    public static function ffrjEmailByCloud($info)/*{{{*/
    {
        require('/opt/php/SendCloud/SendCloudLoader.php');
        $result =   0;
        try {
            $sendCloud = new SendCloud('postmaster@pink.sendcloud.org', 'pXlP3yWF');
            // 如果发现附件不能发送成功，可以尝试这个
            //$sendCloud->convertFilePathEncoding('UTF-8', 'GBK'); 
            $message = new SendCloud\Message();
            // 添加第一个收件人
            $message->addRecipient($info['email']) 
                // 添加批量接受地址
                ->setReplyTo('xxtstudio@163.com') // 添加回复地址
                ->setFromName('粉粉日记') // 添加发送者称呼
                ->setFromAddress('mmcz@fenfenriji.com') // 添加发送者地址
                ->setSubject($info['subject'])  // 邮件主题
                // 邮件正文html形式
                ->setBody($info['body']);
            // 邮件正文纯文本形式，这个不是必须的。
            #   $message->setAltBody('SendCloud PHP SDK 测试正文，请参考');

            $result =   $sendCloud->send($message);
        } catch (Exception $e) {
            $result =   $e->getMessage();
        }    
        return  $result;
    }/*}}}*/
    public static function ffrjEmailByHTTP($info)/*{{{*/
    {
        $url = 'https://sendcloud.sohu.com/webapi/mail.send.json';
        #   不同于登录SendCloud站点的帐号，您需要登录后台创建发信域名，获得对应发信域名下的帐号和密码才可以进行邮件的发送。
        $param  =   array(
                        'api_user'  =>  'postmaster@pink.sendcloud.org',
                        'api_key'   =>  'pXlP3yWF',
                        'from'      =>  'mmcz@fenfenriji.com',
                        'fromname'  =>  '粉粉日记',
                        'to'        =>  $info['email'],
                        'subject'   =>  $info['subject'],
                        'html'      =>  $info['body']
                    );

        $options    =   array('http' => array('method'  => 'POST','content' => http_build_query($param)));
        $context    =   stream_context_create($options);
        $result     =   file_get_contents($url, FALSE, $context);

        return  $result;
    }/*}}}*/
    public static function ffrjEmail($info)/*{{{*/
    {
        return UK::sendCloud($info);
        global $_G;
        if(in_array($_G['serverHost'], array("fc", "fd", "fe", "ff"))){
            return UK::sendCloud($info);
        	//return UK::ffrjEmail_fc($info);
        }

        require("/opt/php/PHPMailer_v5.1/class.phpmailer.php");
        $mail   =   new PHPMailer();                                    #   建立邮件发送类
        $mail->IsSMTP();                                            #   使用SMTP方式发送
        $mail->CharSet  =   'UTF-8';                                #   设置邮件的字符编码
        $mail->Host     =   "mail.fenfenriji.com";                  #   您的企业邮局域名
        $mail->SMTPAuth =   TRUE;                                   #   启用SMTP验证功能
        $mail->Username =   "mmcz@fenfenriji.com";                  #   邮局用户名(请填写完整的email地址)
        $mail->Password =   "2013@xxT";                             #   邮局密码
        $mail->SetFrom("mmcz@fenfenriji.com", "粉粉日记");
        $mail->AddAddress($info['email'], NULL);                    #   收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
        $mail->AddReplyTo("xxtstudio@163.com", "粉粉日记");
        # $mail->AddAttachment("/var/tmp/file.tar.gz");             #   添加附件
        $mail->IsHTML(TRUE); // set email format to HTML            #   是否使用HTML格式
        $mail->Subject  =   $info['subject'];                       #   邮件标题
        $mail->Body     =   $info['body'];                          #   邮件内容
        # $mail->AltBody  =   "This is the body in plain text for non-HTML mail clients";    #   附加信息，可以省略
        $result =   $mail->Send();
        return  $result;
    }/*}}}*/
    
    public static function sendCloud ($param) {
        $url    = "http://sendcloud.sohu.com/webapi/mail.send.json";
        $data = array(
            'api_user'  =>  'postmaster@pink.sendcloud.org',
            'api_key'   =>  '3kkLz0bFbFSsJ16z',
            'from'      =>  'mmcz@fenfenriji.com',
            'fromname'  =>  '粉粉日记',
            'to'        =>  $param['email'],
            'subject'   =>  $param['subject'],
            'html'      =>  $param['body']
        );
    
        $json   = UK::getHttpResponsePOST($url, $data);
        $result = UK::parseData($json);
        if ($result['message'] != 'success'){
            return false;
        }
        return true;
    }
    

    public static function ffrjEmail_fc($info)/*{{{*/
    {
        require(WEB_SERVER_ROOT_PATH."lib/PHPMailer_5.2.10/PHPMailerAutoload.php");
        $mail = new PHPMailer;                                    #   建立邮件发送类
        $mail->IsSMTP();                                            #   使用SMTP方式发送
        $mail->CharSet  =   'UTF-8';                                #   设置邮件的字符编码
        $mail->Host     =   "smtp.exmail.qq.com";                  #   您的企业邮局域名
        $mail->SMTPAuth =   TRUE;                                   #   启用SMTP验证功能
        $mail->Username =   "mmcz@fenfenriji.com";                  #   邮局用户名(请填写完整的email地址)
        $mail->Password =   "2013@xxT";                             #   邮局密码
        $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 465;                                    // TCP port to connect to
        $mail->From = "mmcz@fenfenriji.com";
        $mail->FromName = "粉粉日记";
        $mail->AddAddress($info['email'], NULL);                    #   收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
        $mail->AddReplyTo("xxtstudio@163.com", "粉粉日记");
        $mail->SMTPDebug  = 0;
        # $mail->AddAttachment("/var/tmp/file.tar.gz");             #   添加附件
        $mail->IsHTML(TRUE); // set email format to HTML            #   是否使用HTML格式
        $mail->Subject  =   $info['subject'];                       #   邮件标题
        $mail->Body     =   $info['body'];                          #   邮件内容
        # $mail->AltBody  =   "This is the body in plain text for non-HTML mail clients";    #   附加信息，可以省略
        $result =   $mail->Send();
        return  $result;
    }/*}}}*/

    public static function checkVersion($android, $ios) {
        if(empty($android) || empty($ios)) {
            return false;
        }
        $product_version=    AC::$appInfoList[1];
        $os             =    strtolower(AC::$appInfoList[2]);
        $version = array(
            'android'          =>  $android,
            'ios'              =>  $ios,
        );
        return version_compare($product_version, $version[$os],  '<=');
    }

    /**
     * HTML标签过滤
     * @param $content
     * @param $htmlAllowed
     * @return mixed
     */
    public static function checkHTMLContent($content, $htmlAllowed = ''){
        require_once(dirname(__FILE__) . '/HTMLPurifier.standalone.php');
        $config = HTMLPurifier_Config::createDefault();
        $config->set('HTML.Allowed', $htmlAllowed);
        $config->set('HTML.DefinitionID', 'smzdm library version');
        $config->set('HTML.DefinitionRev', 1);
        //$config->set('Cache.DefinitionImpl', null); // 清理配置缓存,上线时关掉这句
        $def = $config->getHTMLDefinition(true);
        UK::addElementArray($def, AC::$elementArray);
        UK::addAttributeArray($def, AC::$attrArray);
        $purifier = new HTMLPurifier($config);
        $clean_html = $purifier->purify($content);
        return $clean_html;
    }

    /**
     * 批量自定义元素
     * @param $def
     * @param $elementArray
     */
    private static function addElementArray($def, $elementArray){
        foreach ($elementArray as $elementItems) {
            $def->addElement(
                $elementItems['name'],
                $elementItems['type'],
                $elementItems['contents'],
                $elementItems['attr_collections'],
                $elementItems['attributes']
            );
        }
    }

    /**
     * 批量自定义属性
     * @param $def
     * @param $elementArray
     */
    public static function addAttributeArray($def, $elementArray){
        foreach ($elementArray as $elementName => $attr) {
            foreach ($attr as $attrName => $attrDef) {
                $def->addAttribute(
                    $elementName,
                    $attrName,
                    $attrDef
                );
            }
        }
    }

}

